<?php
namespace Crontab;

class Task extends Base
{

    /*
        /usr/bin/php -d display_error /app/cli.php local Task.run
    */
    public function run()
    {
        if(!isNodeNameTaskDaemon()){
            exit('非法操作');
        }
        $serviceSystemTask = $this->get(SERVICE_SYSTEMTASK);
        while(1){
            $list = $serviceSystemTask->getTaskList(1000);
            foreach($list as $systemTask){
                $this->common($serviceSystemTask, $systemTask);
            }
            sleep(1);
        }
    }

    private function common($serviceSystemTask, $systemTask)
    {
        $data = json_decode($systemTask->dry_data, true);
        $url = "{$systemTask->dry_url}?orderNo={$data['order_no']}";
        $response = sendGetByCurl($url);
        $response = json_decode($response, true);
        $bool = false;
        if(is_array($response) && isset($response['code']) && $response['code'] == 0){
            $bool = true;
        }
        $this->update($serviceSystemTask, $systemTask, $bool);
    }

    private function update($serviceSystemTask, $systemTask, $bool)
    {
        $now = getDateTime();
        $update = [
            'dry_try' => $systemTask->dry_try + 1,
            'dry_next_time' => getDateTimeStd($now['timestamp'] + $systemTask->dry_span_time),
            'dry_update_time' => $now['date_time']
        ];
        if($update['dry_try'] >= $systemTask->dry_total || $bool){
            $update['dry_finish'] = 1;
        }
        $serviceSystemTask->update($update, $systemTask->id);
    }

}